﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using hotel.DAL;
using hotel.Common;

namespace hotel.Win.Common
{
    public partial class LoginForm : Form
    {
        private int nLoginCount = 0;

        private const int MAX_LOGIN_COUNT = 3;
        private hotelEntities _context;

        public LoginForm(string id)
        {
            InitializeComponent();
            _context = MyDataContext.GetDataContext;
            lbjdmc.Text = XTCSModel.GetXTCS.JDMC;
            txtid.Text = id;       
        }
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            if (this.DialogResult != DialogResult.Cancel && this.DialogResult != DialogResult.OK)
                e.Cancel = true;
            _context.Dispose();
        }

        private void btnok_Click(object sender, EventArgs e)
        {
            var model = _context.XTYH.FirstOrDefault(p => p.ID == txtid.Text && p.MM == txtmm.Text);

            if (model != null)
            {
                //初始用登陆信息
                UserLoginInfo.UserId = txtid.Text;
                UserLoginInfo.UserName = model.XM;
                UserLoginInfo.Roles = new List<string>();
                foreach (var item in _context.YHJS.Where(p => p.YHID == txtid.Text))
                {
                     UserLoginInfo.Roles.Add(item.JSID);
                     if (item.MRBZ == "是")
                         UserLoginInfo.DefaultRoleName = (EnumRoole)Enum.Parse(typeof(EnumRoole), item.JSID);
                }
               
                
                var log = Log.Instance;
                log.Abstract = LogAbstractEnum.登录系统;
                log.Message = "用户全名[" + UserLoginInfo.FullName + "]";
                log.Info();
                this.Close();

                this.DialogResult = DialogResult.OK;
            }
            else
            {
                // Wrong username or password
                nLoginCount++;
                if (nLoginCount == MAX_LOGIN_COUNT)
                    // Over 3 times
                    this.DialogResult = DialogResult.Cancel;
                else
                {
                    MessageBox.Show("无效的用户名或密码!");
                    txtid.Focus();
                    this.DialogResult = DialogResult.None;
                }
            }
        }

        private void btnclose_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void LoginForm_Shown(object sender, EventArgs e)
        {            
            if (txtid.Text.Length >0)
                txtmm.Focus();
        }      
    }
}
